<script setup lang="ts">
import { computed, h, onMounted, onUnmounted, ref } from 'vue';
import { NButton, NSpace, NTooltip, useDialog } from 'naive-ui';
import { useRoute, useRouter } from 'vue-router';
import mammoth from 'mammoth';
import _ from 'underscore';
import type { DataTableColumns } from 'naive-ui';
import { ChevronBack, RefreshSharp } from '@vicons/ionicons5';
import { useBoolean } from '~/packages/hooks';
import DocumentName from '@/views/document/catalog/modules/document-name.vue';
import ParagraphName from '@/views/document/catalog/modules/paragraph-name.vue';
import WriteDrawer from '@/views/document/catalog/modules/write-drawer.vue';
import AddChapterName from '@/views/document/catalog/modules/add-chapter-name.vue';
import {errorMessage, escapeHTMLManually, generateRandomCode, infoMessage, successMessage} from '@/utils/utils';
import {
  batchInsertCatalogAction,
  batchUpdateCatalogStatusAction,
  deleteCatalogAction,
  fillCatalogAction,
  getCatalogAction,
  getEditDataInfoAction,
  getLogCatalogAction,
  insertChildCatalogAction,
  processDocxAction,
  reRankCatalogAction,
  updateWriteAction
} from '@/service/api';
import CompletedWritingImg from '@/assets/imgs/icon-completed-writing.png';
import NotWritingImg from '@/assets/imgs/icon-not-written.png';
import WritingImg from '@/assets/imgs/icon-writing.png';
import EditImg from '@/assets/imgs/icon-catalog-edit.png';
import DeleteImg from '@/assets/imgs/icon-catalog-delete.png';
import { useRouterPush } from '@/hooks/common/router';
import DownloadModal from '@/views/document/preview/modules/download-modal.vue';
import FormatModal from '@/views/document/preview/modules/format-modal.vue';

const { bool: showDocNameModal, setTrue: openDocNameModal } = useBoolean();
const { bool: showParagraphModal, setTrue: openParagraphModal } = useBoolean();
const { bool: showWriteDrawer, setTrue: openWriteDrawer } = useBoolean();
const { bool: showAddChapterModal, setTrue: openAddChapterModal } = useBoolean();
const { bool: showFormatModal, setTrue: openFormatModal } = useBoolean();
const { bool: showDownloadModal, setTrue: openDownloadModal } = useBoolean();

const { query } = useRoute();
const { routerBack, routerPushByKey } = useRouterPush();

// 是否一键编写
const isOneClickWrite = ref<boolean>(false);
const writingNum = ref<number>(0); // 编写中数量

const generateType = ref<number>(0); // 生成类型 0：正常生成；1：编辑
const taskId = ref<any>(3); // 任务Id
const infoPath = ref<any>(''); // 模板信息文档地址
const zhaoBiaoPath = ref<any>(''); // 招标文件地址（新建上传的）
const catalogPath = ref<any>(''); // 生成的目录文件地址
const knowledgeId = ref<any>(''); // 选取的知识库Id
const fileName = ref<any>('');
const catalogList = ref<any[]>([]);
const catalogRowKeys = ref<any[]>([]);
const showLoading = ref<boolean>(true);
const loadingDes = ref<string>('正在努力处理中，请稍后...');
const writingCatalogList = ref<any[]>([]);
const docInfoObj = ref<any>({
  catalogNum: 0, // 总目录数
  finishNum: 0, // 已编写目录
  waitNum: 0, // 待编写
  wordNum: 0 // 文档总字数
}); // 文档基本信息

const writeTagList = ref<any[]>([
  { id: generateRandomCode(6), title: '已完成', color: '#68BF7B', image: CompletedWritingImg },
  { id: generateRandomCode(6), title: '未编写', color: '#C0C0C0', image: NotWritingImg },
  { id: generateRandomCode(6), title: '编写中', color: '#AE95FF', image: WritingImg }
]);

onMounted(async () => {
  console.log('query: ', query);
  generateType.value = Number.parseInt(query.generateType as string, 10);
  taskId.value = Number.parseInt(query.taskId as string, 10);
  fileName.value = query.fileName;
  // isOneClickWrite.value = Number.parseInt(query.isOneClickWrite as string, 10) === 0;
  infoPath.value = query.infoPath;
  zhaoBiaoPath.value = query.zhaoBiaoPath;
  catalogPath.value = query.catalogPath;

  await getLogCatalogData();
  await queryEditDataInfo();
});

// 查询目录树
async function getLogCatalogData() {
  loadingDes.value = '正在努力处理中，请稍后...';
  showLoading.value = true;
  const { data, error } = await getLogCatalogAction(taskId.value);
  showLoading.value = false;
  if (!error) {
    catalogList.value = data || [];
    if (catalogList.value.length > 0) {
      // 清空所有展开树
      catalogRowKeys.value = [];
      writingNum.value = 0;
      // 默认所有目录全部展开
      getAllCatalogKeys(catalogList.value);
      queryWritingStatusContent(catalogList.value);
      isOneClickWrite.value = writingNum.value > 0;
    } else {
      getHtmlByDocument(catalogPath.value);
    }
  }
}

// 设置所有需要展开的目录
function getAllCatalogKeys(catalogs: any[]) {
  catalogs.forEach(item => {
    item.code = generateRandomCode(8);
    catalogRowKeys.value.push(item.id);

    if (item.children && item.children.length > 0) {
      getAllCatalogKeys(item.children);
    }
  });
}

// 查询是否有编写中的内容
function queryWritingStatusContent(catalogs: any[]) {
  catalogs.forEach(item => {
    if (item.status === 2) {
      writingNum.value += 1;
    }

    if (item.children && item.children.length > 0) {
      queryWritingStatusContent(item.children);
    }
  });
}

// 获取标书编辑数据
async function queryEditDataInfo() {
  const { data, error } = await getEditDataInfoAction(taskId.value);
  if (!error) {
    /** catalogNum :125 //总目录数 finishNum: 1 // 已编写目录 waitNum: 124 // 待编写 generateNum: 10 // 编写中 wordNum: 2352 // 文档总字数 */
    docInfoObj.value = data;
    knowledgeId.value = data.knowledgeName;
  }
}

// 当前生成进度计算
const currentProgress = computed(() => {
  if (docInfoObj.value.finishNum === 0 && docInfoObj.value.catalogNum === 0) {
    return 0;
  }
  return Number.parseFloat(((docInfoObj.value.finishNum / docInfoObj.value.catalogNum) * 100).toFixed(2));
});

// 根据文档获取html内容
function getHtmlByDocument(filePath: string) {
  const { VITE_OTHER_SERVICE_BASE_URL } = import.meta.env;
  const otherUrl = JSON.parse(VITE_OTHER_SERVICE_BASE_URL);
  const docPath_01: string =
    'http://36.155.148.249:8098/xjai-admin/profile/biaoshu_catalog_generate/20240809135508509_tjsk4_20240809140024692.docx';
  const docPath_02: string =
    'http://36.155.148.249:8098/xjai-admin/profile/biaoshu_catalog_generate/20240808135057689_zc2n6_20240808135809319.docx';
  const docPath: string = otherUrl.fileUrl + filePath;
  console.log('docPath: ', docPath);
  fetch(docPath, { cache: 'no-cache' })
    .then(response => response.blob())
    .then(blobData => {
      // console.log("blobData: ", blobData);

      let file: File | null = new File([blobData], `${fileName.value}.docx`, {
        type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        lastModified: Date.now()
      });

      analysisWord(file).then(html => {
        // console.log("docContentHtml.value: ", docContentHtml.value);
      });

      // 文件信息置空
      file = null;
    })
    .catch(error => {
      console.error('发生错误：', error);
      errorMessage('获取文档失败');
    });
}

// 解析word文件，将word转为html
function analysisWord(file: any) {
  return new Promise(resolve => {
    const reader = new FileReader();
    reader.onload = evt => {
      console.log('evt：', evt);
      // 当文件读取完毕后
      // p标签首行没有缩进
      const options = {
        transformDocument: transformElement,
        styleMap: ["p[style-name='Section Title'] => h1:fresh", "p[style-name='Subsection Title'] => h2:fresh"]
      };

      // 调用mammoth组件的方法进行解析文件
      mammoth
        .convertToHtml({ arrayBuffer: evt.target!.result }, options)
        .then(resultObject => {
          // console.log("resultObject: ", resultObject);
          resolve(resultObject.value); // 将处理好的html数据返回
          reader.abort(); // 关闭读取
        })
        .catch(err => {
          console.log('err: ', err);
          reader.abort(); // 关闭读取
        });
    };
    reader.readAsArrayBuffer(file);
    // 启动读取指定的 Blob 或 File 内容：https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader/readAsArrayBuffer
  });
}

// 元素重新定义
function transformElement(element: any) {
  if (element.children) {
    const children: any = _.map(element.children, transformElement);
    element = { ...element, children };
  }

  if (element.type === 'document') {
    // docParagraphList.value = element.children;
    console.log('docParagraphList.value: ', element.children);
    htmlFormat(element.children);
  }

  return element;
}

const firstDefaultObj: any = {
  title: '默认标题',
  code: generateRandomCode(6),
  rankId: 1,
  children: []
};

const secondDefaultObj: any = {
  title: '默认标题',
  code: generateRandomCode(6),
  rankId: 1,
  children: []
};

const thirdDefaultObj: any = {
  title: '默认标题',
  code: generateRandomCode(6),
  rankId: 1,
  children: []
};

const fourthDefaultObj: any = {
  title: '默认标题',
  code: generateRandomCode(6),
  rankId: 1,
  children: []
};

const fifthDefaultObj: any = {
  title: '默认标题',
  code: generateRandomCode(6),
  rankId: 1,
  children: []
};

// 根据文档解析API进行HTML内容拼接封装
async function htmlFormat(docParagraphList: any[]) {
  for (let i: number = 0; i < docParagraphList.length; i++) {
    const paragraphObj: any = docParagraphList[i];
    if (paragraphObj.type === 'paragraph') {
      // 普通段落内容（包括文字和图片）
      let paragraphStr: string = '';

      for (let j: number = 0; j < paragraphObj.children.length; j++) {
        const formatContent = paragraphHtmlFormat(paragraphObj.children[j]);
        paragraphStr += formatContent;
      }

      if (paragraphObj.styleId === 'Heading1' || paragraphObj.styleName === 'heading 1') {
        const titleObj: any = {
          title: paragraphStr,
          code: generateRandomCode(6),
          rankId: 1,
          children: []
        };
        catalogList.value.push(titleObj);
      } else if (paragraphObj.styleId === 'Heading2' || paragraphObj.styleName === 'heading 2') {
        const subTitleObj: any = {
          title: paragraphStr,
          code: generateRandomCode(6),
          rankId: 1,
          children: []
        };
        let parentTitleObj: any;
        if (catalogList.value.length > 0) {
          parentTitleObj = catalogList.value[catalogList.value.length - 1];
        } else {
          catalogList.value.push(firstDefaultObj);
          parentTitleObj = firstDefaultObj;
        }

        parentTitleObj.children.push(subTitleObj);
      } else if (paragraphObj.styleId === 'Heading3' || paragraphObj.styleName === 'heading 3') {
        const titleObj: any = {
          title: paragraphStr,
          code: generateRandomCode(6),
          rankId: 1,
          children: []
        };
        let parentTitleObj: any;
        if (catalogList.value.length > 0) {
          parentTitleObj = catalogList.value[catalogList.value.length - 1];
        } else {
          catalogList.value.push(firstDefaultObj);
          parentTitleObj = firstDefaultObj;
        }
        let subTitleObj: any;
        if (parentTitleObj.children.length > 0) {
          subTitleObj = parentTitleObj.children[parentTitleObj.children.length - 1];
        } else {
          parentTitleObj.children.push(secondDefaultObj);
          subTitleObj = secondDefaultObj;
        }
        subTitleObj.children.push(titleObj);
      } else if (paragraphObj.styleId === 'Heading4' || paragraphObj.styleName === 'heading 4') {
        const titleObj: any = {
          title: paragraphStr,
          code: generateRandomCode(6),
          rankId: 1,
          children: []
        };
        let parentTitleObj: any;
        if (catalogList.value.length > 0) {
          parentTitleObj = catalogList.value[catalogList.value.length - 1];
        } else {
          catalogList.value.push(firstDefaultObj);
          parentTitleObj = firstDefaultObj;
        }
        let subTitleObj: any;
        if (parentTitleObj.children.length > 0) {
          subTitleObj = parentTitleObj.children[parentTitleObj.children.length - 1];
        } else {
          parentTitleObj.children.push(secondDefaultObj);
          subTitleObj = secondDefaultObj;
        }
        let threeTitleObj: any;
        if (subTitleObj.children.length > 0) {
          threeTitleObj = subTitleObj.children[subTitleObj.children.length - 1];
        } else {
          subTitleObj.children.push(thirdDefaultObj);
          threeTitleObj = thirdDefaultObj;
        }
        threeTitleObj.children.push(titleObj);
      } else if (paragraphObj.styleId === 'Heading5' || paragraphObj.styleName === 'heading 5') {
        const titleObj: any = {
          title: paragraphStr,
          code: generateRandomCode(6),
          rankId: 1,
          children: []
        };
        let parentTitleObj: any;
        if (catalogList.value.length > 0) {
          parentTitleObj = catalogList.value[catalogList.value.length - 1];
        } else {
          catalogList.value.push(firstDefaultObj);
          parentTitleObj = firstDefaultObj;
        }
        let subTitleObj: any;
        if (parentTitleObj.children.length > 0) {
          subTitleObj = parentTitleObj.children[parentTitleObj.children.length - 1];
        } else {
          parentTitleObj.children.push(secondDefaultObj);
          subTitleObj = secondDefaultObj;
        }
        let threeTitleObj: any;
        if (subTitleObj.children.length > 0) {
          threeTitleObj = subTitleObj.children[subTitleObj.children.length - 1];
        } else {
          subTitleObj.children.push(thirdDefaultObj);
          threeTitleObj = thirdDefaultObj;
        }
        let fourTitleObj: any;
        if (threeTitleObj.children.length > 0) {
          fourTitleObj = threeTitleObj.children[threeTitleObj.children.length - 1];
        } else {
          threeTitleObj.children.push(fourthDefaultObj);
          fourTitleObj = fourthDefaultObj;
        }
        fourTitleObj.children.push(titleObj);
      } else if (paragraphObj.styleId === 'Heading6' || paragraphObj.styleName === 'heading 6') {
        const titleObj: any = {
          title: paragraphStr,
          code: generateRandomCode(6),
          rankId: 1,
          children: []
        };
        let parentTitleObj: any;
        if (catalogList.value.length > 0) {
          parentTitleObj = catalogList.value[catalogList.value.length - 1];
        } else {
          catalogList.value.push(firstDefaultObj);
          parentTitleObj = firstDefaultObj;
        }
        let subTitleObj: any;
        if (parentTitleObj.children.length > 0) {
          subTitleObj = parentTitleObj.children[parentTitleObj.children.length - 1];
        } else {
          parentTitleObj.children.push(secondDefaultObj);
          subTitleObj = secondDefaultObj;
        }
        let threeTitleObj: any;
        if (subTitleObj.children.length > 0) {
          threeTitleObj = subTitleObj.children[subTitleObj.children.length - 1];
        } else {
          subTitleObj.children.push(thirdDefaultObj);
          threeTitleObj = thirdDefaultObj;
        }
        let fourTitleObj: any;
        if (threeTitleObj.children.length > 0) {
          fourTitleObj = threeTitleObj.children[threeTitleObj.children.length - 1];
        } else {
          threeTitleObj.children.push(fourthDefaultObj);
          fourTitleObj = fourthDefaultObj;
        }
        let fiveTitleObj: any;
        if (fourTitleObj.children.length > 0) {
          fiveTitleObj = fourTitleObj.children[fourTitleObj.children.length - 1];
        } else {
          fourTitleObj.children.push(fifthDefaultObj);
          fiveTitleObj = fifthDefaultObj;
        }
        fiveTitleObj.children.push(titleObj);
      } else {
        console.log('');
      }
    }
  }

  const { data, error } = await batchInsertCatalogAction(taskId.value, catalogList.value);
  console.log('data: ', data);
  if (!error) {
    await getLogCatalogData();
    await queryEditDataInfo();
  }
}

// 段落内容格式化
function paragraphHtmlFormat(paragraphObj: any) {
  let contentStr: string = '';

  if (!paragraphObj.children || paragraphObj.children.length === 0) {
    return '默认标题';
  }

  for (let i: number = 0; i < paragraphObj.children.length; i++) {
    if (paragraphObj.children[i].type === 'text') {
      contentStr = paragraphObj.children[i].value;
      // 如果有html字符串，将其解析为html字符串，就可以正常展示
      contentStr = escapeHTMLManually(contentStr);
    } else {
      contentStr = String(contentStr);
    }
  }

  return contentStr;
}

type RowData = {
  id: number;
  title: string;
  createTime: string;
  rankId: number;
  parentId: number;
  logId: number;
  type: number;
  status: number;
  more3: string;
  ancestors: string;
  children: any;
  firstFlag: number; // 是否是第一级 0否1是
  lastFlag: number; // 是否是最子级 0否1是
};

const selectCatalog = ref<RowData>();
const catalogType = ref<number>(1);

const dialog = useDialog();

const columns: DataTableColumns<RowData> = [
  {
    title: '章节名称',
    key: 'title',
    align: 'left',
    ellipsis: 'EllipsisProps',
    render(item: RowData) {
      let titleStyle: any = {};
      if (item.type === 1) {
        titleStyle = {
          display: 'inline-block',
          fontFamily: 'HarmonyOS Sans SC',
          fontWeight: 'bold',
          maxWidth: '800px',
          fontSize: '20px',
          color: '#333333',
          marginRight: '10px',
          whiteSpace: 'nowrap',
          overflow: 'hidden',
          textOverflow: 'ellipsis'
        };
      } else {
        titleStyle = {
          display: 'inline-block',
          fontFamily: 'HarmonyOS Sans SC',
          fontWeight: '400',
          maxWidth: '700px',
          fontSize: '18px',
          color: '#666666',
          marginRight: '10px',
          whiteSpace: 'nowrap',
          overflow: 'hidden',
          textOverflow: 'ellipsis'
        };
      }
      return h(
        'div',
        { class: 'flex items-center' },
        {
          default: () => [
            h(
              NTooltip,
              { contentStyle: { maxWidth: '600px' } },
              {
                trigger: () => h('span', { style: titleStyle }, item.title),
                default: () =>
                  h(
                    'span',
                    {},
                    {
                      default: () => item.title
                    }
                  )
              }
            ),
            item.type !== 1 &&
              h('img', {
                height: 19,
                width: 19,
                src: item.status === 1 ? NotWritingImg : item.status === 3 ? CompletedWritingImg : WritingImg,
                alt: ''
              }),
            item.status !== 2 &&
              h('img', {
                style: { cursor: 'pointer', marginLeft: '10px', marginRight: '10px' },
                height: 19,
                width: 19,
                src: EditImg,
                alt: '',
                onClick: () => {
                  if (item.status === 2) return;
                  selectCatalog.value = item;
                  openParagraphModal();
                }
              }),
            (!item.children || (item.children && item.children.length === 0)) &&
              item.status !== 2 &&
              h('img', {
                style: { cursor: 'pointer' },
                height: 19,
                width: 19,
                src: DeleteImg,
                alt: '',
                onClick: () => {
                  dialog.error({
                    title: '温馨提示',
                    content: `您确认要删除"${item.title}"章节吗？`,
                    positiveText: '确认',
                    negativeText: '取消',
                    onPositiveClick: async () => {
                      const params: any = {
                        id: item.id,
                        logId: item.logId
                      };
                      const { data, error } = await deleteCatalogAction(params);
                      if (!error) {
                        successMessage('章节删除成功！');
                        await queryEditDataInfo();
                        await getLogCatalogData();
                      }
                    }
                  });
                }
              })
          ]
        }
      );
    }
  },
  {
    title: '操作',
    key: '',
    align: 'right',
    render(item: RowData) {
      return h(
        NSpace,
        { justify: 'end' },
        {
          default: () => [
            item.type !== 6 &&
              (!item.children || (item.children && item.children.length === 0)) &&
              item.status !== 2 &&
              h(
                NButton,
                {
                  type: 'primary',
                  quaternary: true,
                  size: 'small',
                  style:
                    'height: 32px; font-family: HarmonyOS Sans SC; font-weight: 400; font-size: 14px; color: #999999;',
                  onClick: () => {
                    fillCatalogHandle(item);
                  }
                },
                { default: () => '目录扩充' } // 按钮显示名称
              ),
            item.status !== 2 &&
              h(
                NButton,
                {
                  type: 'primary',
                  quaternary: true,
                  size: 'small',
                  style:
                    'height: 32px; font-family: HarmonyOS Sans SC; font-weight: 400; font-size: 14px; color: #999999;',
                  onClick: () => {
                    catalogType.value = 1;
                    selectCatalog.value = item;
                    openAddChapterModal();
                  }
                },
                { default: () => '新增同级章节' }
              ),
            item.type !== 6 &&
              item.status !== 2 &&
              h(
                NButton,
                {
                  type: 'primary',
                  quaternary: true,
                  size: 'small',
                  style:
                    'height: 32px; font-family: HarmonyOS Sans SC; font-weight: 400; font-size: 14px; color: #999999;',
                  onClick: () => {
                    catalogType.value = 2;
                    selectCatalog.value = item;
                    openAddChapterModal();
                  }
                },
                { default: () => '新增下级章节' }
              ),
            item.status !== 2 &&
              item.firstFlag !== 1 &&
              h(
                NButton,
                {
                  quaternary: true,
                  size: 'small',
                  style:
                    'height: 32px; font-family: HarmonyOS Sans SC; font-weight: 400; font-size: 14px; color: #999999;',
                  onClick: () => {
                    catalogMoveUpOrDown(1, item);
                  }
                },
                { default: () => '上移' }
              ),
            item.status !== 2 &&
              item.lastFlag !== 1 &&
              h(
                NButton,
                {
                  quaternary: true,
                  size: 'small',
                  style:
                    'height: 32px; font-family: HarmonyOS Sans SC; font-weight: 400; font-size: 14px; color: #999999;',
                  onClick: () => {
                    catalogMoveUpOrDown(2, item);
                  }
                },
                { default: () => '下移' }
              ),
            item.type === 1 &&
              item.status !== 2 &&
              h(
                NButton,
                {
                  bordered: false,
                  size: 'small',
                  style: 'width: 100px; height: 32px; background: #836FFF; border-radius: 4px; color: #FFFFFF;',
                  onClick: () => quickIntelligentWriting(item)
                },
                { default: () => '快速智写' }
              ),
            item.type !== 1 &&
              item.status === 1 &&
              h(
                NButton,
                {
                  bordered: false,
                  size: 'small',
                  style: 'width: 100px; height: 32px; background: #836FFF; border-radius: 4px; color: #FFFFFF;',
                  onClick: () => {
                    selectCatalog.value = item;
                    openWriteDrawer();
                  }
                },
                { default: () => '精细智写' }
              ),
            item.status === 3 &&
              h(
                NButton,
                {
                  bordered: false,
                  size: 'small',
                  style: 'width: 100px; height: 32px; background: #836FFF; border-radius: 4px; color: #FFFFFF;',
                  onClick: () => {
                    const params: any = {
                      taskId: taskId.value,
                      paragraphId: item.id,
                      generateType: generateType.value,
                      taskId: taskId.value,
                      fileName: fileName.value,
                      infoPath: infoPath.value,
                      zhaoBiaoPath: zhaoBiaoPath.value,
                      catalogPath: catalogPath.value
                    };
                    routerPushByKey('document_preview', { query: params });
                  }
                },
                { default: () => '编辑' }
              )
          ]
        }
      );
    }
  }
];

// 目录扩充
async function fillCatalogHandle(item: RowData) {
  const params: any = {
    task_id: taskId.value,
    catalog_path: {
      title: item.title,
      leval: item.type
    }
  };
  loadingDes.value = '正在进行目录扩充，请稍后...';
  showLoading.value = true;
  const { data, error } = await fillCatalogAction(params);
  showLoading.value = false;
  if (!error) {
    if (data) {
      // data.catalog
      const logList: any[] = [];
      for (let i: number = 0; i < data.catalog.length; i++) {
        const logObj: any = {
          title: data.catalog[i].title
        };
        logList.push(logObj);
      }
      const { data: logData, error: logError } = await insertChildCatalogAction(item.id, logList);
      if (!logError) {
        await getLogCatalogData();
        await queryEditDataInfo();
      }
    } else {
      infoMessage('该章节已无可扩充的子章节');
    }
  }
}

// 目录上下移动 1：上移；2：下移
async function catalogMoveUpOrDown(type: number, item: RowData) {
  const { data, error } = await reRankCatalogAction(item.id, type);
  if (!error) {
    await getLogCatalogData();
    successMessage('移动成功！');
  }
}

// 目录折叠展开
function expandedRowKeysUpdate(keys: Array<string | number>) {
  catalogRowKeys.value = keys;
}

const finishCatalogList = ref<any[]>([]);
const chaptersNum = ref<number>(0);

// 快速智写
function quickIntelligentWriting(item: RowData) {
  // 每次都要先将需要智写的目录列表置空
  writingCatalogList.value = [];
  finishCatalogList.value = [];
  chaptersNum.value = 0;
  getFinishWritingCatalogList([item]);

  console.log('finishCatalogList: ', finishCatalogList.value.length, chaptersNum.value);

  if (finishCatalogList.value.length === chaptersNum.value) {
    dialog.warning({
      title: '温馨提示',
      content: '小主，该章节已完成撰写，是否重新智写。',
      positiveText: '确认',
      negativeText: '取消',
      onPositiveClick() {
        isOneClickWrite.value = true;
        getNeedWritingCatalogList([item], true);
        processDocxService();
      }
    });
  } else if (finishCatalogList.value.length >= 1 && finishCatalogList.value.length < chaptersNum.value) {
    dialog.warning({
      title: '温馨提示',
      content: '小主，检测到当前章节下已有部分子节已完成编写，是否覆盖这些子节继续编写。',
      positiveText: '否',
      negativeText: '是',
      onPositiveClick() {
        isOneClickWrite.value = true;
        getNeedWritingCatalogList([item], false);
        processDocxService();
      },
      onNegativeClick() {
        isOneClickWrite.value = true;
        getNeedWritingCatalogList([item], true);
        processDocxService();
      }
    });
  } else {
    dialog.warning({
      title: '温馨提示',
      content: '小主，将对该章节统一撰写。',
      positiveText: '确认',
      negativeText: '取消',
      onPositiveClick() {
        isOneClickWrite.value = true;
        getNeedWritingCatalogList([item], true);
        processDocxService();
      }
    });
  }
}

// 获取是否有未编写的内容目录
function getFinishWritingCatalogList(catalogs: any[]) {
  catalogs.forEach(item => {
    if (item.status === 3) {
      finishCatalogList.value.push(item);
    }
    chaptersNum.value += 1;

    if (item.children && item.children.length > 0) {
      getFinishWritingCatalogList(item.children);
    }
  });
}

// 修改文档标题
function changeDocumentNameClick() {
  openDocNameModal();
}

// 修改文档标题
function renameHandle(projectName: string) {
  fileName.value = projectName;
}

// 保存精细化编写内容
function saveWriteHandle() {
  queryEditDataInfo();
  getLogCatalogData();
}

// 目录翻新
function catalogRenovationClick() {
  dialog.warning({
    title: '温馨提示',
    content: '小主，你好。目录翻新将会重新对目录进行生成，确定重新生成吗？',
    positiveText: '确认',
    negativeText: '取消',
    onPositiveClick() {
      createNewCatalog();
    }
  });
}

// 目录翻新
async function createNewCatalog() {
  const getParams: any = {
    task_id: taskId.value,
    zhaobiao_path: zhaoBiaoPath.value
  };
  loadingDes.value = '小主，目录翻新中，请稍后...';
  showLoading.value = true;
  const { data, error } = await getCatalogAction(getParams);
  showLoading.value = false;
  if (!error) {
    if (data) {
      catalogPath.value = data.doc_path;
      // 信息更新
      const params: any = {
        id: taskId.value,
        originalFilePath: data.doc_path // 标书目录文档地址
      };
      await updateWriteAction(params);
      const delParams: any = {
        logId: catalogList.value[0].logId
      };
      // 首先要清空当前目录
      const { data: delData, error: delError } = await deleteCatalogAction(delParams);
      if (!delError) {
        // 获取目录树，目录数为空的时候重新插入新的目录树
        await getLogCatalogData();
        await queryEditDataInfo();
      }
      successMessage('目录翻新成功！');
    } else {
      errorMessage('目录翻新失败！');
    }
  }
}

// 下载预览
function downloadPreviewClick() {
  openFormatModal();
}

const formatObj = ref<any>();

// 保存样式设置
function saveFormatSettingHandle(format: any) {
  console.log('设置好的样式：', format);
  formatObj.value = format;

  openDownloadModal();
}

// 一键编写
function oneClickWritingClick() {
  writingCatalogList.value = [];

  if (docInfoObj.value.catalogNum === docInfoObj.value.finishNum) {
    dialog.warning({
      title: '温馨提示',
      content: '小主，所有章节已完成编写，是否重新编写？',
      positiveText: '重新编写',
      negativeText: '取消',
      onPositiveClick() {
        isOneClickWrite.value = true;
        getNeedWritingCatalogList(catalogList.value, true);
        processDocxService();
      }
    });
  } else if (docInfoObj.value.finishNum > 0 && docInfoObj.value.finishNum < docInfoObj.value.catalogNum) {
    dialog.warning({
      title: '温馨提示',
      content: '小主，检测到部份章节已完成编写，请选择重新编写或继续编写。',
      positiveText: '继续编写',
      negativeText: '重新编写',
      onPositiveClick() {
        isOneClickWrite.value = true;
        getNeedWritingCatalogList(catalogList.value, false);
        processDocxService();
      },
      onNegativeClick() {
        isOneClickWrite.value = true;
        getNeedWritingCatalogList(catalogList.value, true);
        processDocxService();
      }
    });
  } else {
    dialog.warning({
      title: '温馨提示',
      content: '小主，将要进行一键编写。',
      positiveText: '确认',
      negativeText: '取消',
      onPositiveClick() {
        isOneClickWrite.value = true;
        getNeedWritingCatalogList(catalogList.value, true);
        processDocxService();
      }
    });
  }
}

// 一键编写请求
async function processDocxService() {
  const catalogIdList: any[] = [];
  for (let i: number = 0; i < writingCatalogList.value.length; i++) {
    const catalogObj: any = writingCatalogList.value[i];
    catalogIdList.push(catalogObj.catalogId);
  }
  const params: any = {
    logId: taskId.value,
    catalogIds: catalogIdList.join(','),
    status: 2 // 1.未编写 2.编写中 3.已编写
  };

  const { data, error } = await batchUpdateCatalogStatusAction(params);
  if (!error) {
    console.log('data: ', data);
    await updateCatalogWritingStatus();
    await getLogCatalogData();
    // oneWritingQueryCatalogStatus();
  } else {
    showLoading.value = false;
    isOneClickWrite.value = false;
  }
}

const timer = ref<any | null>(null);

// 一键编写查询目录状态
function oneWritingQueryCatalogStatus() {
  // 一键编写状态
  if (isOneClickWrite.value && showLoading.value) {
    timer.value = setInterval(() => {
      queryEditDataInfo();
      getLogCatalogData();
    }, 10000);

    if (currentProgress.value >= 100) {
      clearInterval(timer.value);
      timer.value = null;
      showLoading.value = false;
      isOneClickWrite.value = false;
    }
  }
}

// 内容刷新
function refreshClick() {
  queryEditDataInfo();
  getLogCatalogData();
}

onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
});

// 一键编写更新目录状态
async function updateCatalogWritingStatus() {
  const params: any = {
    tenant_id: knowledgeId.value,
    task_id: taskId.value,
    docx_list: [infoPath.value.split(','), writingCatalogList.value],
    zhaobiao_path: zhaoBiaoPath.value
  };
  const { data, error } = await processDocxAction(params);
  if (!error) {
    console.log('一键编写：', data);
  }
}

// 获取需要编写的目录
function getNeedWritingCatalogList(catalogs: any[], isAll: boolean) {
  catalogs.forEach(item => {
    if (isAll) {
      const catalogObj: any = {
        catalogId: item.id,
        title: item.title,
        leval: item.type
      };
      writingCatalogList.value.push(catalogObj);
    } else if (item.status === 1) {
      const catalogObj: any = {
        catalogId: item.id,
        title: item.title,
        leval: item.type
      };
      writingCatalogList.value.push(catalogObj);
    }

    if (item.children && item.children.length > 0) {
      getNeedWritingCatalogList(item.children, isAll);
    }
  });
}

const router = useRouter();

// 返回
function backClick() {
  if (generateType.value === 0) {
    routerPushByKey('root');
  } else {
    routerBack();
  }
}
</script>

<template>
  <NLayout :native-scrollbar="false">
    <NSpin :show="showLoading" :description="loadingDes" :rotate="false" size="large">
      <template #icon>
        <img src="@/assets/imgs/spin-loading.gif" alt="" width="240" height="240" />
      </template>
      <div class="content-box">
        <div class="header-box">
          <div class="content-header">
            <div class="header-top">
              <div class="left-top">
                <span class="name-text">{{ fileName.length > 15 ? fileName.substring(0, 15) + '...' : fileName }}</span>
                <img class="name-img" src="@/assets/imgs/icon-name-edit.png" alt="" @click="changeDocumentNameClick" />
              </div>
              <div v-if="isOneClickWrite" class="writing-tips">
                <span class="tips-text">小主，内容正在快速生成中，为保证撰写质量，我们需要一点点时间...</span>
                <span class="tips-text">通过点击【刷新】按钮，可持续查看生成情况...</span>
              </div>
              <NButton v-if="isOneClickWrite" class="refresh-btn" strong quaternary @click="refreshClick">
                <NIcon size="20" color="#666666">
                  <RefreshSharp />
                </NIcon>
                刷新
              </NButton>
            </div>
            <div class="content-left">
              <div class="catalog-msg-box">
                <div class="right-top">
                  <span class="number-text">总章节：{{ docInfoObj.catalogNum }}</span>
                  <span class="number-text">已完成：{{ docInfoObj.finishNum }}</span>
                  <span class="number-text">总字数：{{ docInfoObj.wordNum }}</span>
                </div>
                <div class="tag-box">
                  <div v-for="item in writeTagList" :key="item.id" class="tag-item">
                    <img class="tag-img" :src="item.image" alt="" />
                    <span class="tag-title" :style="{ color: item.color }">{{ item.title }}</span>
                  </div>
                </div>
              </div>
              <div class="writ-progress-box">
                <NProgress
                  type="line"
                  color="#B99FFF"
                  rail-color="#ffffff"
                  :height="34"
                  :border-radius="4"
                  :percentage="currentProgress"
                  :fill-border-radius="0"
                  indicator-text-color="#333333"
                  indicator-placement="inside"
                >
                  <template #default>
                    <span>{{ currentProgress === 100 ? '已编辑完成：' : '当前已完成编写：' }}{{ currentProgress }}%</span>
                  </template>
                </NProgress>
              </div>
              <NSpace>
                <NButton
                  class="write-btn"
                  strong
                  quaternary
                  :disabled="isOneClickWrite"
                  @click="catalogRenovationClick"
                >
                  <template #icon>
                    <img src="@/assets/imgs/icon-catalog-renovation.png" width="21" alt="" />
                  </template>
                  目录翻新
                </NButton>
                <NButton
                  class="setting-btn"
                  strong
                  quaternary
                  :disabled="isOneClickWrite"
                  @click="downloadPreviewClick"
                >
                  <template #icon>
                    <img src="@/assets/imgs/icon-format.png" width="16" alt="" />
                  </template>
                  设置格式并预览下载
                </NButton>
                <NButton class="write-btn" strong quaternary :disabled="isOneClickWrite" @click="oneClickWritingClick">
                  <template #icon>
                    <img src="@/assets/imgs/icon-document-write.png" width="16" alt="" />
                  </template>
                  一键编写
                </NButton>
                <NButton class="back-btn" strong quaternary @click="backClick">
                  <NIcon size="20" color="#666666">
                    <ChevronBack />
                  </NIcon>
                  返回
                </NButton>
              </NSpace>
            </div>
          </div>
          <div class="shadow-line"></div>
        </div>
        <NDataTable
          :columns="columns"
          :data="catalogList"
          :row-key="(item: any) => item.id"
          max-height="100%"
          :expanded-row-keys="catalogRowKeys"
          default-expand-all
          striped
          @update:expanded-row-keys="expandedRowKeysUpdate"
        />
      </div>
    </NSpin>
    <DocumentName v-model:show="showDocNameModal" :task-id="taskId" :project-name="fileName" @refresh="renameHandle" />
    <ParagraphName
      v-model:show="showParagraphModal"
      :catalog-obj="selectCatalog"
      @save-paragraph-name="getLogCatalogData"
    />
    <AddChapterName
      v-model:show="showAddChapterModal"
      :type="catalogType"
      :catalog-obj="selectCatalog"
      @save-chapter-name="getLogCatalogData"
    />
    <WriteDrawer
      v-model:visible="showWriteDrawer"
      :task-id="taskId"
      :knowledge-id="knowledgeId"
      :catalog-obj="selectCatalog"
      :zhaobiao-path="zhaoBiaoPath"
      :info-path="infoPath"
      @save-write="saveWriteHandle"
    />
    <FormatModal v-model:show="showFormatModal" @save-format-setting="saveFormatSettingHandle" />
    <DownloadModal v-model:show="showDownloadModal" :task-id="taskId" :title="fileName" :format-obj="formatObj" />
  </NLayout>
</template>

<style scoped lang="scss">
.bg-layout {
  padding: 16px 16px 0 !important;
  background: url('@/assets/imgs/edit-bg.png');
  background-size: 100% 100%;
}
.content-box {
  background: rgba(229, 231, 253, 0.6);
  border-radius: 12px;
  border: 1px solid #faf9fd;
  padding: 40px 40px 0px 40px;
  margin: 17px 15px 0;
  position: sticky;
  top: 0;
}
:deep(.n-spin) {
  width: auto;
  height: auto;
}
:deep(.n-data-table-th__title) {
  font-weight: bold;
  font-size: 22px;
  color: #333333;
  padding: 0 30px;
}
.background-btn {
  width: 140px;
  height: 42px;
  background: linear-gradient(180deg, #e877ae, #7c73f3);
  border-radius: 4px;
  font-weight: 400;
  font-size: 16px;
  color: #ffffff;
  line-height: 42px;
  border: none;
}
.header-box {
  display: flex;
  flex-direction: column;
  background: rgba(229, 231, 253, 0.6);
  position: sticky;
  top: 0;
  z-index: 100;
  .content-header {
    display: flex;
    flex-direction: column;
    background-color: #ffffff;
    height: 122px;
    width: 100%;
    //box-shadow: 0px 0px 40px 0px rgba(131, 111, 255, 0.1);
    border-top-left-radius: 12px;
    border-top-right-radius: 12px;
    padding: 10px 30px;
    .header-top {
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;
      .left-top {
        display: flex;
        flex-direction: row;
        align-items: center;
        .name-text {
          font-weight: bold;
          font-size: 24px;
          color: #333333;
          line-height: 49px;
        }
        .name-img {
          width: 23px;
          height: 25px;
          margin-left: 15px;
          cursor: pointer;
        }
        .status-box {
          display: flex;
          flex-direction: row;
          align-items: center;
          margin-left: 100px;
          .status-img {
            width: 18px;
            height: 18px;
            margin-right: 5px;
          }
          .status-img-gif {
            width: 32px;
            height: 32px;
            margin-right: 5px;
          }
          .status-text {
            font-size: 16px;
            color: #0d6fb8;
          }
        }
      }
      .writing-tips {
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-right: 325px;
        .tips-text {
          font-size: 16px;
          color: #836fff;
        }
      }
      .refresh-btn {
        width: 100px;
        height: 40px;
        background: #ffffff;
        border-radius: 4px;
        border: 1px solid #836fff;
      }
    }
    .content-left {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      .catalog-msg-box {
        display: flex;
        flex-direction: column;
        .right-top {
          display: flex;
          flex-direction: row;
          align-items: center;
          .number-text {
            margin-right: 25px;
            font-weight: 400;
            font-size: 16px;
            color: #666666;
            line-height: 30px;
          }
        }
        .tag-box {
          display: flex;
          flex-direction: row;
          align-items: center;
          margin-top: 5px;
          .tag-item {
            display: flex;
            flex-direction: row;
            align-items: center;
            margin-right: 20px;
            .tag-img {
              width: 12.5px;
              height: 12.5px;
              margin-right: 5px;
            }
            .tag-title {
              font-weight: 400;
              font-size: 12px;
            }
          }
        }
      }
      .writ-progress-box {
        display: flex;
        flex-direction: row;
        align-items: center;
        width: 600px;
        background: #ffffff;
        padding: 3px;
        border-radius: 4px;
        border: 1px solid #836fff;
        //.progress-title {
        //  margin-right: 15px;
        //  color: #333333;
        //}
      }
      .write-btn {
        width: 130px;
        height: 40px;
        background: #ffffff;
        border-radius: 4px;
        border: 1px solid #836fff;
      }
      .setting-btn {
        width: 180px;
        height: 40px;
        background: #ffffff;
        border-radius: 4px;
        border: 1px solid #836fff;
      }
      .back-btn {
        width: 100px;
        height: 40px;
        background: #ffffff;
        border-radius: 4px;
        border: 1px solid #836fff;
      }
    }
  }
  .shadow-line {
    width: 100%;
    height: 14px;
    background: linear-gradient(180deg, #9585b1 0%, rgba(166, 180, 202, 0.01) 69%);
  }
}
</style>
